package com.zeoy.keeplivetestdemo.service;

import android.app.Notification;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.zeoy.keeplivetestdemo.R;
import com.zeoy.keeplivetestdemo.aidl.KeepLiveAidlInterface;
import com.zeoy.keeplivetestdemo.utils.ServiceCheckUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2018\3\21 0021.
 */

public class BackGroundService extends Service implements MediaPlayer.OnCompletionListener{
    public static final int FLOG = 1001;
    private IBinder binder;
    private ServiceConnection connec_notifi, connec_foregron;
    private Intent intent_notifi, intent_foregron;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==0)

            Toast.makeText(getApplicationContext(),"后台运行中",Toast.LENGTH_SHORT).show();
        }
    };

    private MediaPlayer mediaPlayer;

    @Override
    public void onCreate() {
        super.onCreate();
       /* EventBus.getDefault().register(this);
        message = new ServiceMessage(FLOG);
        if (!thread.isAlive())
            thread.start();
*/
        initData();
        //无声音乐保活

        mediaPlayer = MediaPlayer.create(this, R.raw.equal);
        mediaPlayer.setOnCompletionListener(this);

    }

    private void initData() {

        intent_notifi = new Intent(this, NotificationListenerService.class);
        connec_notifi = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {

            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.e("zeoy", "【后台   -  断开连接通知  -  启动通知】");
                startService(intent_notifi);
                bindService(intent_notifi, connec_notifi, BIND_IMPORTANT);
            }
        };

        intent_foregron = new Intent(this, ForeGroundService.class);
        connec_foregron = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {

            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.e("zeoy", "【后台   -  断开连接前台  -  启动前台】");
                startService(intent_foregron);
                bindService(intent_foregron, connec_foregron, BIND_IMPORTANT);
            }
        };

        binder = new KeepLiveAidlInterface.Stub() {
            @Override
            public String getServiceName() throws RemoteException {
                return "NotificationListenerService";
            }
        };
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (Build.VERSION.SDK_INT < 18) {
            startForeground(FLOG, new Notification());
            stopForeground(true);
        } else {
            Intent intent1 = new Intent(this, BackGroundService.GrayInnerService.class);
            startService(intent1);
            startForeground(FLOG, new Notification());
            stopForeground(true);
        }

        Log.e("zeoy", "【后台重新启动】");

        if (!ServiceCheckUtils.isServiceWorked(this, "com.zeoy.keeplivetestdemo.service.NotificationListenerService")) {
            //启动通知服务
            startService(intent_notifi);
            Log.e("zeoy", "【后台   -  启动  -  通知】");
        }
        bindService(intent_notifi, connec_notifi, BIND_IMPORTANT);
        /*if (!ServiceCheckUtils.isServiceWorked(this, "com.zeoy.keeplivetestdemo.service.ForeGroundService")) {
            //启动前台服务
            Log.e("zeoy", "【后台   -  启动  -  前台】");
            startService(intent_foregron);
        }
        bindService(intent_foregron, connec_foregron, BIND_IMPORTANT);*/
        if (!thread.isAlive()){
            thread.start();
        }
        if(!mediaPlayer.isPlaying()){
            mediaPlayer.start();
            mediaPlayer.setVolume(0f,0f);
        }
        return START_STICKY;
    }


    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }


    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            Timer timer = new Timer();
            TimerTask task = new TimerTask() {

                @Override
                public void run() {
                  handler.sendEmptyMessage(0);
                }
            };
            timer.schedule(task, 0, 5000);
        }
    });

    @Override
    public void onDestroy() {
        super.onDestroy();
        /*EventBus.getDefault().unregister(this);
        //重启自己
        Intent intent = new Intent(getApplicationContext(), ForeGroundService.class);
        startService(intent);*/
    }

    @Override
    public void onCompletion(MediaPlayer mp) {

        mp.start();
    }

    //新线程移除掉前台提示（灰色保活）
    public static class GrayInnerService extends Service {

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            startForeground(FLOG, new Notification());
            stopForeground(true);
            stopSelf();
            return super.onStartCommand(intent, flags, startId);
        }

        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

    }

}
